package com.wobito.common.utils;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.lang.UUID;
import cn.hutool.json.JSONUtil;
import com.wobito.pojo.dto.user.AccessToken;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;

import java.nio.charset.StandardCharsets;
import java.util.Date;
import java.util.List;

/**
 * JWT工具类
 */
public class JwtUtil {

    //有效期为 1个小时
    public static final Integer JWT_TTL = 60 * 60 * 24;
    public static final String JWT_KEY = "goodlab";
    public static final String secretKey = "cereshuzhitingnizhenbangcereshuzhitingnizhenbang";

    /**
     * 返回载荷信息
     *
     * @param token token
     * @return 载荷信息
     */
    public static AccessToken verifyTokenByRSA(String token) {
        AccessToken payloadDto = AccessToken.builder().build();
        try {
            Claims claims = Jwts.parser()
                    .setSigningKey(secretKey.getBytes(StandardCharsets.UTF_8))
                    .parseClaimsJws(token)
                    .getBody();
            BeanUtil.copyProperties(claims, payloadDto);
            return payloadDto;
        } catch (Exception e) {
            return null;
        }

    }

    public static Claims parseJWT(String secretKey, String token) {
        // 得到DefaultJwtParser
        Claims claims = Jwts.parser()
                // 设置签名的秘钥
                .setSigningKey(secretKey.getBytes(StandardCharsets.UTF_8))
                // 设置需要解析的jwt
                .parseClaimsJws(token).getBody();
        return claims;
    }

    /**
     * 生成token
     *
     * @param userName    用户名
     * @param authorities 用户权限
     * @return token
     */
    public static String createAccessToken(String userName, List<String> authorities) {
        SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256;
        Date now = new Date();
        Date exp = DateUtil.offsetSecond(now, JWT_TTL);  //一个小时过期
        //设置载荷
        AccessToken payloadDto = AccessToken.builder()
                .sub(JWT_KEY)
                .iat(now.getTime())
                .exp(exp.getTime())
                .jti(UUID.randomUUID().toString())
                .username(userName)
                .authorities(authorities)
                .build();
        //创建建造者对象
        JwtBuilder jwts = Jwts.builder()
                .setPayload(JSONUtil.toJsonStr(payloadDto)) //设置载荷
                .setHeaderParam("alg", "HS256") // 设置头
                .setHeaderParam("typ", "JWT")  //设置签证
                .signWith(signatureAlgorithm, secretKey.getBytes(StandardCharsets.UTF_8));
        //生成token
        return jwts.compact();
    }
}

